// 定义包名
package com.atguigu.lease.web.app.service.impl;

// 导入所需的类
import com.atguigu.lease.common.constant.RedisConstant;

import com.atguigu.lease.common.exception.LeaseExcetion;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.CodeUtils;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

// 使用@Service注解标记这个类为Spring的服务组件
@Service
public class LoginServiceImpl implements LoginService {
    // 自动注入SmsService的实例
    @Autowired
    private SmsService smsService;
    // 自动注入StringRedisTemplate的实例
    @Autowired
    private StringRedisTemplate redisTemplate;
    // 自动注入UserInfoMapper的实例
    @Autowired
    private UserInfoMapper userInfoMapper;

    // 实现LoginService接口的getCode方法，用于获取验证码
    @Override
    public void getCode(String phone) {
        // 生成验证码
        String code = CodeUtils.getCode(6);
        // 构造Redis的key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        // 检查是否已经存在验证码
        Boolean b = redisTemplate.hasKey(key);
        if (b) {
            // 如果存在，获取当前验证码的剩余有效期
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            // 如果剩余有效期小于允许重新发送的时间，则抛出异常
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseExcetion(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        // 发送验证码
        smsService.sendCode(phone, code);
        // 将验证码存储到Redis，并设置有效期
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    // 实现LoginService接口的login方法，用于登录
    @Override
    public String login(LoginVo loginVo) {
        // 检查电话号码是否为空
        if (loginVo.getPhone() == null) {
            throw new LeaseExcetion(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        // 检查验证码是否为空
        if (loginVo.getCode() == null) {
            throw new LeaseExcetion(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        // 构造Redis的key
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        // 从Redis获取验证码
        String andSet = redisTemplate.opsForValue().get(key);
        // 检查验证码是否为空或已过期
        if (andSet == null) {
            throw new LeaseExcetion(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        // 检查验证码是否正确
        if (!andSet.equals(loginVo.getCode())) {
            throw new LeaseExcetion(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        // 构造查询条件
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());

        // 查询用户信息
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        // 如果用户不存在，则创建新用户
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setNickname("用户" + loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoMapper.insert(userInfo);
        } else {
            // 如果用户存在，检查用户状态是否被禁用
            if (userInfo.getStatus().equals(BaseStatus.DISABLE)) {
                throw new LeaseExcetion(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
            }
        }

        // 使用JwtUtil生成JWT令牌
        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
    }

    @Override
    public UserInfoVo getloginbyid(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo=new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());

        return userInfoVo;
    }
}